package com.hsylient.websocket.endpoint;

import cn.hutool.core.util.StrUtil;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/ws")
public class WebSocketEndpoint {

    private static final Map<String, Session> sessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        sessions.put(session.getId(), session);
        log.info("[WebSocket] 开始新建会话 sessionId:[{}]", session.getId());
        sendMessage(session, StrUtil.format("[WebSocket] 新建会话完成 sessionId:[{}]", session.getId()));
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("[WebSocket] 会话[{}] 接收到来自客户端的消息 {}", session.getId(), message);
        for (;;) {
            broadcast(message);
        }
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session.getId());
        log.info("[WebSocket] 会话[{}] 关闭", session.getId());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("[WebSocket] 会话[{}] 出现异常 [{}]", session.getId(), error.getMessage());
    }

    private void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("[WebSocket] 会话[{}] 推送消息的时候出现异常 [{}]", session.getId(), e.getMessage());
        }
    }

    private void broadcast(String message) {
        sessions.forEach((id, session) -> {
            if (session.isOpen()) {
                sendMessage(session, message);
            } else {
                sessions.remove(id);
            }
        });
    }
}